/*
 *	This file is part of File To Phone <http://code.google.com/p/filetophone/>
 *	
 *	File To Phone is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *	
 *	File To Phone is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *	
 *	You should have received a copy of the GNU General Public License
 *	along with File To Phone.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  Adopted from the Apache License 2-licensed chrometophone project by Google Inc.
 *	
 */
package com.google.android.c2dm.server;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class SendServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(SendServlet.class.getName());
	private static final String OK_STATUS = "OK";
	private static final String ERROR_STATUS = "ERROR";

    private final static String F2P_EXTRA_URL = "url";
    private final static String F2P_EXTRA_TYPE = "type";
    private final static String F2P_EXTRA_TYPE_FTP = "ftp";
    
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doGet(req, resp);
	}
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		
		/*String extHeader = req.getHeader("X-FileToPhone");  // simple XSRF protection
		if (extHeader == null) {
			resp.setStatus(400);
			resp.getWriter().println(ERROR_STATUS + " Please use the File To Phone tool, " +
				" available at http://code.google.com/p/filetophone/");
			log.warning("Would block send");
			//return;  // TODO working for now
		} else {
		    log.info("Got X-FileToPhone header");
		}*/
		
		String type = req.getParameter(F2P_EXTRA_TYPE);
		String url = req.getParameter(F2P_EXTRA_URL);
		/*if (type == null || url == null || !type.equals(F2P_EXTRA_TYPE_FTP)) {
		    resp.setStatus(400);
		    resp.getWriter().println(ERROR_STATUS + " (Must specify valid type (only 'ftp' for now) and url parameters)");
		    return;
		}*/
		 				
		//UserService userService = UserServiceFactory.getUserService();
		//User user = userService.getCurrentUser();
		/*if (user != null) {*/
		 PersistenceManager pm =
             C2DMessaging.getPMF(getServletContext()).getPersistenceManager();
		 Key k = KeyFactory.createKey(DeviceInfo.class.getSimpleName(), "pepitolospa@gmail.com");
		 DeviceInfo device = pm.getObjectById(DeviceInfo.class, k);
		    C2DMessaging push = C2DMessaging.get(getServletContext());
		    Map<String, String[]> params = new HashMap<String, String[]>();
		    params.put("cadena", new String[]{"hola"});
 		    push.sendNoRetry(device.getDeviceRegistrationID(), "sdasfd","cadena","hola","cadena2","adios");

		/*} else {
		    String followOnURL = req.getRequestURI() + 
	                "?type=" + URLEncoder.encode(type, "UTF-8") +
		            "&url=" + URLEncoder.encode(url, "UTF-8");
		    resp.sendRedirect(userService.createLoginURL(followOnURL));
		}*/
    }

    private boolean doSendToPhone(String type, String url, 
            String userAccount, HttpServletResponse resp) throws IOException {
        // Get device info
        DeviceInfo deviceInfo = null;
        // Shared PMF
        PersistenceManager pm =
                C2DMessaging.getPMF(getServletContext()).getPersistenceManager();
        try {
            Key key = KeyFactory.createKey(DeviceInfo.class.getSimpleName(), userAccount);
            try {
                deviceInfo = pm.getObjectById(DeviceInfo.class, key);
            } catch (JDOObjectNotFoundException e) {
                log.warning("User unknown");
                resp.setStatus(400);
                resp.getWriter().println(ERROR_STATUS + " (User unknown)");
                return false;
            }
        } finally {
            pm.close();
        }

        // Send push message to phone
        C2DMessaging push = C2DMessaging.get(getServletContext());
        if (push.sendNoRetry(deviceInfo.getDeviceRegistrationID(),
                "" + url.hashCode(), F2P_EXTRA_TYPE, type, F2P_EXTRA_URL, url)) {
            log.info("Link sent to phone!");
            resp.getWriter().println(OK_STATUS);
            return true;
        } else {
            log.warning("Error: Unable to send link to phone.");
            resp.setStatus(500);
            resp.getWriter().println(ERROR_STATUS + " (Unable to send link)");
            return false;
        }
    }
}
